package com.cs.controller;

import com.cs.context.BaseContext;
import com.cs.dto.EditUserDTO;
import com.cs.dto.RegisterUserDTO;
import com.cs.dto.UserLoginDTO;
import com.cs.exception.BaseException;
import com.cs.result.Result;
import com.cs.service.UserService;
import com.cs.vo.GetInfoUserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
@Api(tags = "用户操作")
@CrossOrigin//解决跨域问题
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    @ApiOperation("用户注册")
    public Result register(@RequestBody RegisterUserDTO userDto) {
        log.info("用户注册,用户信息为{}", userDto);
        return userService.register(userDto);
    }

    /**
     * 用户登录
     *
     * @param
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result login(@RequestBody UserLoginDTO userLoginDTO) {
        log.info("用户登录,用户信息为{}", userLoginDTO);
        String token = userService
                .login(userLoginDTO.getUsername(), userLoginDTO.getPassword(), userLoginDTO.getRole());
        return Result.success(token);
    }

    /**
     * 获取当前用户信息
     *
     * @return
     */
    @GetMapping("/info")
    @ApiOperation("根据id获取用户信息")
    public Result<GetInfoUserVO> getUserInfo() {
        log.info("获取id为{}的用户信息", BaseContext.getCurrentId());
        GetInfoUserVO getInfoUserVO = userService.getUserInfo(BaseContext.getCurrentId());
        return Result.success(getInfoUserVO);
    }

    /**
     * 编辑用户信息
     *
     * @param userDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改用户信息")
    public Result<String> updateUserInfo(@RequestBody EditUserDTO userDTO) {
        log.info("修改用户信息,被修改后的信息为{}", userDTO);
        userService.updateUserInfo(userDTO);
        return Result.success();
    }
}
